<?php

namespace App\Services;

use App\Exceptions\InternalException;
use App\Exceptions\InvalidRequestException;
use App\Models\Role;
use App\Models\RoleUser;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class RoleUserService
{
    public function get($search,$project_id,$type = 'company'){
        $sql = RoleUser::select('id','name','status','auth','created_at','project_id')->with('parent')->with('roles')->when($search, function ($query, $search) {
            return $query->where(function($query) use ($search) {
                $query->where('name','like', '%'.$search.'%');
            });
        })
        ->when($project_id, function ($query, $project_id) {
            return $query->where(function($query) use ($project_id) {
                $query->where('project_id',$project_id);
            });
        });
        return $sql;
    }

    public function insert($input){

        $is = RoleUser::where('role_id',$input['role_id'])->where('project_id',$input['project_id'])->where('user_id',$input['user_id'])->first();
        if($is){
            throw new InvalidRequestException('这个角色已存在');
        }
        try {
            $data = RoleUser::create($input);
            if($data){
                return $data;
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th->getMessage()));
            throw new InternalException('提交失败');
        }
    }

    public function update($input){
        $res = [];
        foreach ($input as $k => $v) {
            if($v || $v == 0){
                $res[$k] = $v;
            }
        }
        unset($res['id']);
        try {
            $data = RoleUser::where('id',$input['id'])->update($res);
            if($data){
                return $data;
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }
}